<template>
  <div class="my_main">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="120px" label-position="top">
        <el-col :span="12">
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="formData.userName" disabled placeholder="默认用户登录用户名" :maxlength="11" show-word-limit
              clearable :style="{ width: '82%' }"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类别" prop="type">
            <el-select v-model="formData.type" placeholder="请选择类别" style="width: 82%;">
              <el-option v-for="dict in dict.type.user_auth_role_type_one" :key="dict.value" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label=" 姓 名" prop="authenticationName">
            <el-input v-model="formData.authenticationName" placeholder="请输入姓名" clearable :style="{ width: '82%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="医生职称" prop="doctorRank">
            <el-select v-model="formData.doctorRank" placeholder="请选择医生职称" style="width: 82%;">
              <el-option v-for="dict in dict.type.user_auth_doctor_rank" :key="dict.value" :label="dict.label"
                :value="dict.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="所属医院" prop="hospitalName">
            <el-select v-model="formData.hospitalName" filterable :filter-method="mySearch" placeholder="请选择所属医院"
              style="width: 82%;">
              <el-option v-for="params in hospList" :key="params.id" :label="params.hospitalName"
                :value="params.hospitalName">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="授权账号" prop="authorizedAccountId">
            <div style="display: flex;width: 82%;">
              <el-select v-model="authorizedAccountId" disabled multiple placeholder="授权账号">
                <el-option v-for="item in authMyList" :key="item.value" :label="item.accountName"
                  :value="item.accountId">
                </el-option>
              </el-select>

              <el-form-item label-width="20px" label="" style="margin-left: 30px;">
                <el-button type="primary" size="mini" style="height: 36px;" @click="toAuth"> +新授权 </el-button>
              </el-form-item>
            </div>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="5">
          <el-form-item label-width="20px" label="">
            <el-button type="primary" size="mini" @click="toAuth"> +新授权 </el-button>
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="电子邮箱" prop="email">
            <el-input v-model="formData.email" placeholder="请输入电子邮箱" clearable :style="{ width: '82%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="联系方式" prop="tel">
            <el-input v-model="formData.tel" placeholder="请输入联系方式" clearable :style="{ width: '82%' }">
            </el-input>
          </el-form-item>
        </el-col>
      
        <!-- <el-col :span="12">
          <el-form-item label="邮政地址" prop="postalAddress">
            <el-input v-model="formData.postalAddress" placeholder="请输入邮政地址" clearable :style="{ width: '82%' }">
            </el-input>
          </el-form-item>
        </el-col> -->

        <el-col :span="12">
          <el-form-item label="医师从业证" prop="valiDoctor" required>
            <el-upload ref="media" :file-list="mediafileList" :limit="1" :action="mediaAction" :auto-upload="true"
              :on-error="upFail" :before-upload="uploadBeforeUpload" :on-success="uploadContent" :headers="headers"
              :data="{ folderType: 7 }" :show-file-list="false"
              :before-remove="() => { formData.valiDoctor = false; mediafileList = [] }">
              <div class="box_add">
                <div v-if="mediafileList.length > 0">
                  <img :src="mediafileList[0].url" width="370" height="185">
                  <div style="color:#165DFF ;font-size: 18px;"
                    @click.stop="() => { formData.valiDoctor = false; mediafileList = [] }">删除</div>
                </div>
                <div v-if="mediafileList.length < 1"><i class="el-icon-plus" style="font-size: 30px"></i></div>
                <div class="el-upload__text" v-if="mediafileList.length < 1">支持扩展名:.png、jpeg、.jpg，最大10M</div>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>

        <el-col :span="12">
            <el-form-item label="邮政地址" prop="postalAddress">
              <el-input v-model="formData.postalAddress" placeholder="请输入邮政地址" clearable :style="{ width: '83%' }">
              </el-input>
            </el-form-item>
          <div style="line-height: 26px;font-weight: bold;font-size: 16px;padding-bottom: 5px;">科普目的：</div>
          <div style="border:  1px dashed #ccc;width: 83%;;border-radius: 8px;">
            <div style="padding: 20px 5px 0 20px;">
              <el-checkbox-group v-model="createPurpose" size="medium">
                <el-checkbox v-for="(item, index) in checkListOptions" :key="index" :label="item.value"
                  :disabled="item.disabled">{{ item.label }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-col>
        <el-col :span="24">
          <el-form-item label="简 介" prop="shortDescription">
            <el-input v-model="formData.shortDescription" placeholder="请输入简介" clearable :style="{ width: '91%' }">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" style="margin-top: 40px">
          <el-form-item size="large" style="text-align: center;width: 90%;">
            <el-button type="primary" @click="submitForm">保存认证信息</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
    
  </div>
</template>

<script>
import { getScanCodeAuthUrl, authenticationDataUser, systemAuthLists, getInfoByUserId, UpdateDataUser, getHospitalInfo } from '@/api/my'
import { getToken } from "@/utils/auth";
export default {
  dicts: ['user_auth_doctor_rank', 'user_auth_role_type_one'],
  components: {},
  props: ['openHandle'],
  data() {
    return {
      validateFile: (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择一个文件'));
        } else {
          callback();
        }
      },
      jobList: [   //职称类别
        {
          "label": "医务从业者",
          "value": "1"
        },
        {
          "label": "其他",
          "value": "2"
        }
      ],
      hospList: [   //职称类别
        // {
        //   "label": "郑州大学第一附属医院",
        //   "value": "1"
        // },
        // {
        //   "label": "洛阳骨科医院",
        //   "value": "2"
        // },
        // {
        //   "label": "郑州市人民医院",
        //   "value": "3"
        // },
      ],
      authMyList: [],
      createPurpose: [],              //科普目的
      authorizedAccountId: undefined,  //授权账号
      formData: {
        valiDoctor: '',   //验证是否上传用
        userName: '',  //用户手机号
        type: undefined,  //类别
        doctorRank: undefined,    //医生职称
        hospitalName: undefined,   //所属医院名称
        authenticationName: undefined,  // 姓 名
        authorizedAccountId: undefined,  //授权账号
        shortDescription: undefined,     //简 介
        email: undefined,                //电子邮箱
        tel: undefined,                 //联系方式
        postalAddress: undefined,       //邮政地址
        createPurposes: [],              //科普目的,为了表单验证
        createPurpose: [],              //科普目的
        proofUrl: '',                     //凭证资料url（多个资料，号分隔）
        roleType: 1,                  //认证类型创作者（1：个人认证资料 2：机构认证资料）3：新媒体4：审核者
      },
      headers: {
        Authorization: "Bearer " + getToken()
      },
      rules: {
        userName: [{
          required: true,
          message: '默认用户登录用户名',
          trigger: 'blur'
        }, {
          // pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          required: true,
          message: '请输入联系方式',
          trigger: 'blur'
        }],
        ///^([a-zA-Z0-9_.&*-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$/; 
        type: [{
          required: true,
          message: '请选择类别',
          trigger: 'blur'
        }],
        authenticationName: [{
          required: true,
          message: '请输入 姓 名',
          trigger: 'blur'
        }],
        authorizedAccountId: [],
        shortDescription: [],
        email: [
          {
            required: true,
            message: '电子邮件格式错误',
            trigger: 'blur'
          }, {
            pattern: /^([a-zA-Z0-9_.&*-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)$/,
            message: '电子邮件格式错误',
            trigger: 'blur'
          }
        ],
        media: [
          { required: true, validator: this.validateFile, trigger: 'change' },
        ],
        tel: [{
          required: true,
          message: '请填写联系方式',
          trigger: 'blur'
        },
          //  {
          //   pattern: /^1(3|4|5|7|8|9)\d{9}$/,
          //   message: '手机号格式错误',
          //   trigger: 'blur'
          // }
        ],
        postalAddress: [],
        createPurpose: [{
          required: true,
          type: 'array',
          message: '请至少选择一个科普目的',
          trigger: 'change'
        }],
        valiDoctor: [{
          required: true,
          message: '请选择上传医生从业证',
          trigger: 'change'
        }],
      },
      mediafileList: [],
      imgHeader: process.env.VUE_APP_ImgUrlHeader,
      mediaAction: process.env.VUE_APP_BASE_API + "/common/resourceFileUpload",
      // uploadAction: process.env.VUE_APP_BASE_API + "/common/commonFileUpload",
      uploadfileList: [],
      docListOptions: [{
        "label": "医务从业人员",
        "value": "isDoctor"
      }],
      checkListOptions: [{
        "label": "课题管理",
        "value": 1
      }, {
        "label": "公益科普",
        "value": 2
      }, {
        "label": "文化传播",
        "value": 3
      }, {
        "label": "创作协同",
        "value": 4
      }, {
        "label": "健康科普",
        "value": 5
      }, {
        "label": "中医问诊",
        "value": 6
      }],
    }
  },
  computed: {
    imgEndUrl(url) {
      // return 123
      return (url) => {
        //  console.log(url,123);
        // const url = "https://ossapi.169000.net/zyykp/sourceMaterialImg/2024/01/22/hushi_20240122152939A001.jpeg";
        const filenameRegex = /.*\/([^/]*?)$/;
        const match = url.match(filenameRegex);
        if (match) {
          return match[1]
          console.log(match[1]);  // 输出: hushi_20240122152939A001.jpeg  
        } else {
          console.log("没有找到文件名");
          return url
        }
      }
    }
  },
  watch: {
    openHandle(ne, ol) {
      console.log(ne)
      if (!ne) {
        this.removeDoc()
      }
      this.init()
      //console.log(ne,123);
    }
  },
  async created() {
    this.AuthList()
    this.init()
  },
  mounted() { 

  },
  methods: {
    mySearch(Userinput) {
      this.getHosList({ hospitalName: Userinput })
      //console.log(e,111000);
    },
    async getHosList(name) {
      let res = await getHospitalInfo(name)
      this.hospList = res.data
      // console.log(res,121212);
    },
    removeDoc() {
      this.mediafileList = []
      this.formData.valiDoctor = []
      this.$refs['elForm'].resetFields()
    },
    init() {
      this.getHosList()
      this.getAuthMyList()
      // console.log();

    },
    fileDel() { //关闭前清空上传的校验和上传列表
      this.$refs['media'].uploadFiles = []  //关闭素材要清空上传列表
      this.formData.valiDoctor = null           //校验
    },
    async getAuthMyList() {
      // if (this.$store.state.user.roles[0] == 'ordinaryUser') {
      //   this.formData.userName = this.$store.state.user.phone  //用户手机号
      //   this.formData.authenticationName = this.$store.state.user.nickName  // 姓 名
      //   return
      // }
      // console.log(121212);
      let res = await getInfoByUserId(this.$store.state.user.userId)
      //  let r = res.data.map(v =>{
      //       v.createPurpose = Number(v.createPurpose)
      //       return v
      //     })
      if (this.authMyList.length > 0) {
        this.authorizedAccountId = this.authMyList.reduce((pre, value, index) => {
          pre.push(value.accountId)
          return pre
        }, [])
        // this.authorizedAccountId = [...this.authMyList] 
      }

      if (res.code == 200 && !this.isEmptyObject(res.data) && res.data.roleType == 1) {
        this.formData.email = res.data.email
        this.formData.postalAddress = res.data.postalAddress
        this.formData.proofUrl = res.data.proofUrl
        this.mediafileList = [{ url: this.imgHeader + res.data.proofUrl, name: this.imgEndUrl(res.data.proofUrl) }]
        this.formData.roleType = res.data.roleType
        this.formData.shortDescription = res.data.shortDescription
        this.formData.tel = res.data.tel
        // console.log(this.formData.doctorRank);
        if (res.data.doctorRank) {
          this.formData.doctorRank = res.data.doctorRank.toString()
        }

        // let findJob = this.dict.type.user_auth_doctor_rank.find(v=>res.data.doctorRank == v.value)
        // if(findJob !== undefined) this.formData.doctorRank = findJob.label
        if (res.data.type) {
          this.formData.type = res.data.type.toString()
        }

        this.formData['userDataId'] = res.data?.userDataId
        this.formData.hospitalName = res.data?.hospitalName
        this.formData.userId = res.data?.userId
        this.formData.userName = res.data?.userName
        this.formData.authenticationName = res.data?.authenticationName
        if (res.data.createPurpose.length > 0) {
          this.createPurpose = res.data.createPurpose.split(',')
          this.createPurpose = this.createPurpose.map(v => Number(v))
        }
        //console.log(this.authMyList.length,'ppp');
        if (this.authMyList.length > 0) {
          this.authorizedAccountId = this.authMyList.reduce((pre, value, index) => {
            pre.push(value.accountId)
            return pre
          }, [])
          // this.authorizedAccountId = [...this.authMyList] 
        }
        // this.formData.authorizedAccountId =  res.data.authorizedAccountList.map(v=>{
        // })
      } else {
        if (res.data.userDataId) {
          this.formData['userDataId'] = res.data.userDataId
        }
        this.formData.userName = this.$store.state.user.phone  //用户手机号
        this.formData.authenticationName = this.$store.state.user.nickName  // 姓 名
      }
      this.formData.userName = this.$store.state.user.phone  //用户手机号
        this.formData.authenticationName = this.$store.state.user.nickName  // 姓 名
      //  console.log(res);
    },
    isEmptyObject(obj) {
      return JSON.stringify(obj) === '{}';
    },
    async AuthList() {  //授权列表
      let res = await systemAuthLists({ userId: this.$store.state.user.userId })
      if (res.code == 200) {
        this.authMyList = res.rows
      }
      //console.log(res,'----');
    },
    async toAuth() {  //新授权
      let res = await getScanCodeAuthUrl(this.$store.state.user.userId)
      window.location.href = res.data;
      // console.log(res);
      // alert(123)
    },
    async save() {
      //console.log(this.formData);
      // return
      this.formData.createPurpose = this.createPurpose.join()
      if (this.formData.userDataId !== undefined) {
        let result = await UpdateDataUser(this.formData)
        if (result.code == 200) {
          this.$message.success({
            title: '提示',
            message: '更新认证成功'
          })
        }
        this.$refs['media'].uploadFiles = []  //关闭素材要清空上传列表
        this.formData.valiDoctor = null           //校验
        this.$emit('closeDia', { name: 'chuangzuozhe', isClose: false })
        return
      }
      // console.log(this.formData,'ppp');
      let res = await authenticationDataUser(this.formData)
      if (res.code == 200) {
        this.$message.success({
          title: '提示',
          message: '操作成功，请重新登录，正在退出登录'
        })
        this.$emit('closeDia', { name: 'chuangzuozhe', isClose: false })
        this.$message.success({ title: '提示', message: res.msg })
        // this.$store.dispatch('LogOut').then(() => {
        //     location.href = '/index';
        // })
      }
      // console.log(res,'sdfsdf');
      //this.$refs.media.submit();
    },
    upFail(err, file, fileList) {
      //上传失败
      // console.log(err,'llll');
      this.$message.error('上传失败，请稍后再重试')
    },
    submitForm() {
      if (this.$refs['media'].uploadFiles.length < 1) {
        this.formData.valiDoctor = null
      } else {
        this.formData.valiDoctor = true  //如果上传就赋值，下面会通过验证，然后再清空赋值
      }
      this.$refs['elForm'].validate(valid => {
        if (this.formData.valiDoctor == null) return
        if (!valid) return
        this.save()
        // TODO 提交表单
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    uploadBeforeUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
      if (!isImage) {
        this.$message.error('应该选择png，jpg，jpeg类型的文件');
        return false;
      }
      let isRightSize = file.size / 1024 / 1024 < 10
      if (!isRightSize) {
        this.$message.error('文件大小超过 10MB')
        return false
      }

      return isRightSize && isImage
    },
    submitUpload() {
      this.$refs['upload'].submit()
    },
    uploadContent(response, file, fileList) {  //内容封面
      this.mediafileList = []
      if (response.code == 200) {
        this.formData.proofUrl = response.data.filePath
        this.formData.valiDoctor = response.data.filePath
        // console.log(this.formData.proofUrl, 'sssss');
        // this.form.coverUrl = response.data.filePath
        this.mediafileList.push({ url: response.data.url + response.data.filePath, name: this.imgEndUrl(response.data.filePath) })
        this.$message.success({
          title: '提示',
          message: '上传医师从业证成功'
        })
      } else {
        this.formData.valiDoctor = []
        this.$message.info('上传图片失败，请稍后重试')
      }
      //  console.log(response, 123);
    },
    mediaBeforeUpload(file, fileList) {
      //console.log('aaa',file);
      const isJPG = file.type === 'image/jpeg';
      let isRightSize = file.size / 1024 / 1024 < 10
      if (!isJPG) {
        this.$message.error('只能上传image/jpeg')
      }
      if (!isRightSize) {
        this.$message.error('文件大小超过 10MB')
      }
      return isRightSize && isJPG
      // console.log(file,fileList,'erwer');
      //  return isRightSize
    },
  }
}

</script>

<style lang="scss" scoped>
// ::v-deep .el-select__tags-text{
//   margin-top: -20px;
// }
.my_main {
  padding-left: 100px;
  margin-top: 40px;
}

.el-upload__tip {
  line-height: 1.2;
}
</style>

<style lang="scss" scoped>
::v-deep .el-select {
  width: 410px;
}

::v-deep .el-upload-dragger {
  width: 330px !important;
}

.box_add {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  width: 370px;
  height: 185px;
  border: 1px dashed #ccc;
  border-radius: 8px;
  margin-top: 10px;
}

.el-scrollbar__wrap {
  overflow-x: hidden !important;
}

::v-deep .el-checkbox {
  margin-right: 20px;
  margin-bottom: 20px;
}
</style>
